package com.weijianhuawen.wjblog.jwt.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weijianhuawen.wjblog.common.utils.Response;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: 处理json参数
 * @date: 2024-10-16 22:57
 */

public class ResultUtil {

    /**
     * 请求成功响应参数
     * @param response 响应体
     * @param result 响应结果
     * @throws IOException 异常
     */
    public static void ok(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();

        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }

    /**
     * 失败响应
     * @param response 响应体
     * @param result 前后端约定响应格式
     * @throws IOException
     */
    public static void fail(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");

        ObjectMapper mapper = new ObjectMapper();
        PrintWriter writer = response.getWriter();
        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }

    /**
     * 失败响应参数 自定义响应码
     * @param response
     * @param status
     * @param result
     * @throws IOException
     */
    public static void fail(HttpServletResponse response, int status, Response<?> result) throws IOException {
        response.setContentType("application/json");
        response.setStatus(status);
        response.setCharacterEncoding("UTF-8");

        PrintWriter writer = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();

        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }
}
